<template>
    <div>
        <Row :gutter="16" class="flex-style">
            <!-- <Col span="7">商户名称
                <Select
                    :loading="loadingClients"
                    :remote-method="handleSearchClients"
                    class="flex-items"
                    clearable
                    filterable
                    placeholder="输入商户手机号/名称搜索"
                    remote
                    v-model="filterData.client_id"
                >
                    <Option :key="index" :value="option.id" v-for="(option, index) in clients">{{option.name + ' ' + option.user.telephone}}</Option>
                </Select>
            </Col> -->

            <Col span="7">城市列表
                <Select class="flex-items" clearable filterable placeholder="不限" v-model="filterData.region_code">
                    <Option :key="item.region_code" :value="item.region_code" v-for="item in cityList">{{ item.name }}</Option>
                </Select>
            </Col>

            <Col span="17">保修日期
                <Select
                    @on-change="guaranteeChange"
                    clearable
                    placeholder="不限"
                    style="width: 100px;margin-left: 5px;"
                    v-model="guaranteeState"
                >
                    <Option :value="0">已过保</Option>
                    <Option :value="1">保期内</Option>
                </Select>

                <DatePicker
                    :options="guaranteeStartOption"
                    @on-change="guarantee_begin_change"
                    class="flex-items"
                    placeholder="开始时间"
                    type="date"
                    v-model="guarantee_begin"
                ></DatePicker>

                &nbsp;-&nbsp;
                <DatePicker
                    :options="guaranteeEndOption"
                    @on-change="guarantee_end_change"
                    class="flex-items"
                    placeholder="结束时间"
                    type="date"
                    v-model="guarantee_end"
                ></DatePicker>
            </Col>
        </Row>

        <Row :gutter="16" class="flex-style" style="padding: 15px 0;">
            <!-- <Col span="7">商户标签
                <Select class="flex-items" clearable placeholder="商户标签" v-model="filterData.client_tag">
                    <Option :key="tag.id" :value="tag.id" v-for="tag in clientTags">{{tag.name}}</Option>
                </Select>
            </Col> -->

            <Col span="7">设备状态
                <Select class="flex-items" clearable placeholder="不限" v-model="filterData.state">
                    <Option :value="1">待交付</Option>
                    <Option :value="2">已交付已绑定</Option>
                    <Option :value="3">已下线被替换</Option>
                    <Option :value="4">已下线被退货</Option>
                    <Option :value="5">已交付被丢失</Option>
                    <Option :value="6">已交付被拆回</Option>
                    <Option :value="7">已交付被解绑</Option>
                </Select>
            </Col>

            <Col span="17">交付时间
                <DatePicker 
                class="flex-items" 
                @on-change="bill_begin_change"
                placeholder="开始时间" 
                type="date" 
                v-model="bill_begin"></DatePicker>

                &nbsp;-&nbsp;
                <DatePicker 
                @on-change="bill_end_change" 
                class="flex-items" 
                placeholder="结束时间" 
                type="date" 
                v-model="bill_end"></DatePicker>
            </Col>
        </Row>

        <Row :gutter="16" class="flex-style">
            <Col span="7">购买渠道
                <Select class="flex-items" clearable placeholder="不限" v-model="filterData.distribution_channel">
                    <Option :value="1">线上销售</Option>
                    <Option :value="2">合同采购</Option>
                </Select>
            </Col>

            <Col span="7">查关键字
                <Input class="flex-items" clearable placeholder="完整设备SN / 房源地址 / 小区名称" style="width: 200px" v-model.trim="filterData.keyword"/>
            </Col>

            <Col span="10">产品型号
                <Select
                    @on-change="modelChange"
                    clearable
                    placeholder="不限"
                    style="width: 110px;margin-left: 5px"
                    v-model="filterData.device_type"
                >
                    <Option :key="item.id" :value="Number(item.id)" v-for="item in device_types">{{item.name}}</Option>
                </Select>

                <Select class="flex-items" clearable placeholder="不限" v-model="filterData.product_id">
                    <Option :key="item.id" :value="item.id" v-for="item in productsAct">{{item.name}}</Option>
                </Select>

                <Button :loading="searchFlag" @click="getData(1, 1)" style="margin-left: 5px" type="primary">搜索</Button>
            </Col>
        </Row>
        <br>

        <div class="device-count">
            当前条件下设备总数共
            <strong>{{deviceTotal}}</strong> 个，其中:
            <span class="device-count-item" v-for="(item,index) in deviceStatistics">
                <span v-if="index>0">,</span>
                <span class="device-name">{{item.name}}</span>
                <span class="device-num">{{item.count}}</span>个
            </span>
        </div>

        <div style="text-align:right;margin-bottom:10px;">
            <Button @click="download" type="primary">数据导出</Button>
        </div>

        <reportListTable :loading="loading" :tableInfo="report_detail_list" @goDetail="goDetail"></reportListTable>

        <Page
            :page-size="filterData.limit"
            :total="report_detail_list.num"
            @on-change="toPage"
            ref="pager"
            show-elevator
            show-total
            style="text-align: center; margin-top: 20px;"
        />
    </div>
</template>

<script>
import debounce from 'lodash/debounce'
import { http, api } from '@/libs/http'
import { startOfDay, endOfDay } from '@/libs/date'
import reportListTable from './report-list-table.vue'

export default {
  components: {
    reportListTable
  },
  data () {
    return {
      loading: false,
      clients: [], // 商铺列表
      loadingClients: false,
      clientTags: [], // 商户标签

      searchFlag: false,
      searchType: 1, // 搜索类型，1->列表，2->统计
      guaranteeState: '', // 保修状态，是否已过保
      device_types: [], // 产品型号1列表
      products: [], // 产品型号2列表全部内容
      productsAct: [], // 产品型号2列表当前联动内容
      guarantee_begin: '',
      guarantee_end: '',
      bill_begin: '',
      bill_end: '',
      filterData: {
        // 条件筛选区域当前显示所选条件
        client_id: '', // 商铺名称对应的商户id
        region_code: '', // 城市码
        guarantee_begin: '', // 保修开始日期
        guarantee_end: '', // 保修截至日期
        client_tag: '', // 商户标签
        state: '', // 设备状态
        bill_begin: '', // 交付开始时间
        bill_end: '', // 交付结束时间
        product_id: '', // 产品型号1
        device_type: '', // 产品型号2
        distribution_channel: '', // 购买渠道
        keyword: '', // 搜索关键词
        limit: 10
      },
      searchData: {}, // 当前表格数据所使用筛选条件
      guaranteeStartOption: {}, // 保修日期datepicker禁选范围
      guaranteeEndOption: {}, // 保修日期datepicker禁选范围
      report_detail_list: {
        list: [],
        num: 0
      },
      report_detail_count: {
        list: [],
        num: 0
      },
      deviceStatistics: {},
      deviceTotal: 0
    }
  },
  computed: {
    cityList () {
      return this.$store.state.ticket.allCities
    }
  },

  mounted () {
    this.getDevModel()
    this.getData(1, 1)
    // this.getClientTags();
  },

  methods: {
    toPage (page) {
      this.getData(page, 2)
    },
    /**
         * page( Number ) / 跳转页码
         * type( Number ) / 1->搜索，2->翻页(默认)
         * flag( Number ) / 查找内容，1->明细（默认），2->统计
         */
    async getData (page, type, flag) {
      if (type === 1) {
        this.searchData = this.deepClone(this.filterData)
        for (let key in this.searchData) {
          if (!this.searchData[key]) {
            delete this.searchData[key]
          }
        }
        if (this.searchData.bill_begin) this.searchData.bill_begin = startOfDay(this.searchData.bill_begin)
        if (this.searchData.bill_end) this.searchData.bill_end = endOfDay(this.searchData.bill_end)
      }
      this.searchData.offset = (page - 1) * this.searchData.limit
      let urlObj = {}
      if (this.searchType === 1) {
        urlObj = api.devices_list
      } else {
        urlObj = {}
      }
      this.loading = true
      http.request(this, urlObj, null, this.searchData, res => {
        this.loading = false
        if (res) {
          this.report_detail_count.list = res.device_states
          this.report_detail_count.num = res.count || 0

          this.report_detail_list.list = res.device_states
          this.report_detail_list.num = res.count || 0
          this.report_detail_list.list.forEach(item => {
            item.devInfo = {
              id: item.id,
              name: item.product_name,
              sn: item.sn,
              tags: []
            }
            if (item.model_name) {
              item.devInfo.tags.push(item.model_name)
            }
            // bind_channel, item.distribution_channel
            if (item.bind_channel === 1) {
              item.devInfo.tags.push('云丁绑定')
            } else if (item.bind_channel === 2) {
              item.devInfo.tags.push('商户绑定')
            }

            if (item.distribution_channel === 1) {
              item.devInfo.tags.push('线上销售')
            } else if (item.distribution_channel === 2) {
              item.devInfo.tags.push('合同采购')
            }

            item.addr = {
              shop: item.client_name,
              address: item.address
            }

            item.guarantee = {
              time: '',
              state: ''
            }

            if (item.guarantee_begin && item.guarantee_end) {
              item.guarantee.time = `${item.guarantee_begin} 至 ${item.guarantee_end}`
              if (new Date(item.guarantee_end).getTime() < new Date().getTime()) {
                item.guarantee.state = '已过保'
              } else if (item.guarantee_begin && item.guarantee_end) {
                item.guarantee.state = '保期内'
              }
            }
          })
          if (type === 1) {
            this.$refs.pager.currentPage = 1
          }
        }
        this.isLoadig = false
      })

      // 设备总数统计
      const params = Object.assign({}, this.searchData)
      delete params.limit
      delete params.offset
      const deviceStatistics = await http.fetch(this, api.device_statistics, null, params)
      this.deviceStatistics = Object.values(deviceStatistics)
      this.calculateDeviceCount()
    },

    calculateDeviceCount () {
      this.deviceTotal = 0
      this.deviceStatistics.forEach(item => {
        this.deviceTotal += item.count
      })
    },

    getClientTags () {
      const params = {
        limit: 1000,
        offset: 0
      }
      http.request(this, api.tags_list, null, params, (res, err) => {
        if (res) {
          this.clientTags = res.rows
        }
      })
    },

    handleSearchClients: debounce(function (keyword) {
      this.searchClients(keyword)
    }, 300),
    async searchClients (keyword) {
      if (keyword) {
        const params = {
          limit: 20,
          offset: 0,
          keyword
        }
        this.loadingClients = true
        const res = await http.fetch(this, api.ticket_clients_list, null, params)
        if (res && res.length > 0) this.clients = res
        this.loadingClients = false
      }
    },
    getDevModel () {
      http.request(this, api.dev_model_list, null, null, res => {
        if (res) {
          this.device_types = res.device_types
          this.products = res.products
          this.productsAct = this.deepClone(this.products)
        }
      })
    },
    goDetail (label, id) {
      this.$emit('goDetail', label, id)
    },
    // 导出报表
    download () {
      let data = this.deepClone(this.searchData)
      delete data.offset
      delete data.limit

      http.exportTable(this, api.export_report_table, null, data)
    },
    modelChange (res) {
      this.filterData.product_id = ''
      if (!res) {
        return (this.productsAct = this.deepClone(this.products))
      }
      this.productsAct = this.products.filter(item => {
        return res === item.device_type
      })
    },
    deepClone (src, tar = {}) {
      for (let key in src) {
        if (!src.hasOwnProperty(key)) {
          return false
        }
        if (typeof src[key] === 'object') {
          tar[key] = src[key].constructor === Array ? [] : {}
          this.deepClone(src[key], tar[key])
        } else {
          tar[key] = src[key]
        }
      }
      return tar
    },
    /**
         *  @desc 根据保修状态设置datepicker默认值和不可选范围
         */
    guaranteeChange (val) {
      this.filterData.guarantee_begin = ''
      this.filterData.guarantee_end = ''
      this.guarantee_begin = ''
      this.guarantee_end = ''
      if (this.guaranteeState === 1) {
        // 保期内。左边datepicker为当天，右边datepicker为空。左边datepicker禁选过去日期
        this.guarantee_begin = new Date()
        this.filterData.guarantee_begin = this.guarantee_begin.getTime()
        this.guaranteeStartOption = {
          disabledDate: date => {
            return date && date.valueOf() < Date.now() - 86400000
          }
        }
        this.guaranteeEndOption = {
          disabledDate: date => {
            return date && date.valueOf() < Date.now() - 86400000
          }
        }
      } else if (this.guaranteeState === 0) {
        // 已过保。左边datepicker为空，右边datepicker为昨天。右边datepicker禁选当天及未来时间
        this.guarantee_end = new Date(new Date() - 24 * 60 * 60 * 1000)
        this.filterData.guarantee_end = this.guarantee_end.getTime()
        this.guaranteeEndOption = {
          disabledDate: date => {
            return date && date.valueOf() > Date.now() - 86400000
          }
        }
        this.guaranteeStartOption = {
          disabledDate: date => {
            return date && date.valueOf() > Date.now() - 86400000
          }
        }
      } else {
        this.guaranteeStartOption = {}
        this.guaranteeEndOption = {}
      }
    },
    tabChange (name) {
      if (name === 'count') {
        this.searchType = 2
      } else if (name === 'list') {
        this.searchType = 1
      }
    },
    guarantee_begin_change (time) {
      let begin = new Date(time).getTime()
      if (this.filterData.guarantee_end && begin > this.filterData.guarantee_end) {
        this.filterData.guarantee_begin = ''
        this.guarantee_begin = ''
        return this.$Message.error('不可大于结束时间')
      } else {
        this.filterData.guarantee_begin = begin
      }
    },
    guarantee_end_change (time) {
      let end = new Date(time).getTime()
      if (this.filterData.guarantee_begin && end < this.filterData.guarantee_begin) {
        this.filterData.guarantee_end = ''
        this.guarantee_end = ''
        return this.$Message.error('不可小于开始时间')
      } else {
        this.filterData.guarantee_end = end
      }
    },
    bill_begin_change (time) {
      let begin = new Date(time).getTime()
      if (this.filterData.bill_end && begin > this.filterData.bill_end) {
        this.filterData.bill_begin = ''
        this.bill_begin = ''
        return this.$Message.error('不可大于结束时间')
      } else {
        this.filterData.bill_begin = begin
      }
    },
    bill_end_change (time) {
      let end = new Date(time).getTime()
      if (this.filterData.bill_begin && end < this.filterData.bill_begin) {
        this.filterData.bill_end = ''
        this.bill_end = ''
        return this.$Message.error('不可小于开始时间')
      } else {
        this.filterData.bill_end = end
      }
    }
  }
}
</script>

<style lang="less" scoped>
.label {
    display: inline-block;
    width: 100px;
}
.flex-style {
    & > .ivu-col {
        display: flex;
        align-items: center;
        .flex-items {
            flex: 1;
            margin-left: 5px;
        }
    }
}
.device-count {
    line-height: 1.8;
    padding: 10px;
    margin-bottom: 10px;
    background-color: #efeff0;
    .device-count-item {
        margin-left: 2px;
        .device-num {
            font-weight: bold;
            margin-left: 2px;
        }
    }
}
</style>
